package 力扣._54_螺旋矩阵;

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        int direct = 0; //0右，1下，2左，3上
        int[][] action = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int[][] visted = new int[matrix.length][matrix[0].length];
        List<Integer> result = new ArrayList<>();

        int i = 0, j = 0;
        int next_i, next_j;
        while (0 <= i && i < matrix.length && 0 <= j && j < matrix[0].length && visted[i][j] == 0) {
            visted[i][j] = 1;
            result.add(matrix[i][j]);
            next_i = i + action[direct][0];
            next_j = j + action[direct][1];
            if (0 <= next_i && next_i < matrix.length && 0 <= next_j && next_j < matrix[0].length && visted[next_i][next_j] == 0) {
                i = next_i;
                j = next_j;
            } else {
                direct = (direct + 1) % 4;
                i = i + action[direct][0];
                j = j + action[direct][1];
            }
        }
        return result;
    }
}
